using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using StudentManager.Models;

namespace StudentManager.Controllers;

public class StudentsController : Controller
{
    private readonly StudentDbContext _db;

    public StudentsController()
    {
        _db = new StudentDbContext();
    }
    [HttpGet]
    public IActionResult Index()
    {
        var stu = _db.Students.Where(x => x.IsDelete == false).ToList();
        return View(stu);
    }
    [HttpPost]
    public IActionResult Index(string keyword)
    {
        keyword = string.IsNullOrEmpty(keyword) ? "" : keyword.Trim();
        var stu = _db.Students.Where(x => x.IsDelete == false).ToList();
        if (string.IsNullOrEmpty(keyword))
        {
            return View(stu);
        }
        var tmpStu = stu.Where(x => x.StudentId.ToString().Contains(keyword) || x.StudentName.Contains(keyword)).ToList();
        return View(tmpStu);
    }
    public IActionResult Create()
    {
        return View();
    }
    [HttpPost]
    public IActionResult Create(Student input)
    {
        if (_db.Students.Any(x => x.StudentId.Equals(input.StudentId)))
        {
            return View("Create");
        }
        _db.Students.Add(input);
        _db.SaveChanges();
        return RedirectToAction("Index");
    }
    public IActionResult Delete(int id)
    {
        var stu = _db.Students.FirstOrDefault(x => x.Id == id);
        return View(stu);
    }
    public IActionResult DeleteConfirm(int StudentId)
    {
        var stu = _db.Students.FirstOrDefault(x => x.StudentId == StudentId);
        if (stu != null)
        {
            stu.IsDelete = true;
            _db.SaveChanges();
            return RedirectToAction("Index");
        }
        return NotFound();
    }
    public IActionResult Edit(int id)
    {
        var stu = _db.Students.FirstOrDefault(x => x.Id == id);
        return View(stu);
    }
    [HttpPost]
    public IActionResult Edit(Student input)
    {
       var stu = _db.Students.FirstOrDefault(x => x.Id == input.Id);
        if (stu != null)
        {
            stu.StudentId = input.StudentId;
            stu.StudentName = input.StudentName;
            _db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(stu);
    }
}